package bookstore.servlet;

import bookstore.bound.auth.EnrollForm;
import bookstore.bound.auth.LoginForm;
import bookstore.bound.auth.UsernameForm;
import bookstore.manager.AuthManager;
import bookstore.manager.UserManager;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthServlet {
    protected AuthManager authManager;
    protected UserManager userManager;

    public AuthServlet(AuthManager authManager, UserManager userManager) {
        System.out.println(String.format("Constructor of %s", this.getClass().getName()));
        this.authManager = authManager;
        this.userManager = userManager;
    }

    @GetMapping("/")
    public Map authCheck(HttpSession session) {
        return authManager.authCheck(session);
    }

    @PostMapping("/enroll")
    public Object enroll(HttpSession session, @RequestBody @Valid EnrollForm enrollForm, BindingResult errors) {
        System.out.println(this.getClass().getName());

        errors.hasErrors();
        return userManager.enroll(session, enrollForm);
    }

    @PostMapping("/login")
    public Object login(HttpSession session, @RequestBody @Valid LoginForm loginForm, BindingResult errors) {
        errors.hasErrors();
        return authManager.login(session, loginForm);
    }

    @GetMapping("/username")
    public Map checkUsername(@RequestParam("username") String username) {
        return userManager.checkUsername(username);
    }

    @PostMapping("/username")
    public Map setUserName(HttpSession session, @RequestBody @Valid UsernameForm usernameForm, BindingResult errors) {
        authManager.requireLogin(session);
        errors.hasErrors();
        return userManager.setUsername(session, usernameForm);
    }
}
